'use client';

import { useState, useEffect, useRef } from 'react';
import styled from 'styled-components';
import * as Cesium from 'cesium';
import { droneLocationService } from '@/services/mqtt';
import { DroneLocationData, MqttConnectionStatus } from '@/services/mqtt/types';

// 连接状态指示器样式
const ConnectionStatus = styled.div<{ status: MqttConnectionStatus }>`
  position: absolute;
  top: 10px;
  right: calc(22% + 20px);
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 100;
  display: flex;
  align-items: center;
  background-color: ${props => {
    switch(props.status) {
      case MqttConnectionStatus.CONNECTED: return 'rgba(40, 167, 69, 0.8)';
      case MqttConnectionStatus.CONNECTING: return 'rgba(255, 193, 7, 0.8)';
      case MqttConnectionStatus.RECONNECTING: return 'rgba(255, 193, 7, 0.8)';
      case MqttConnectionStatus.ERROR: return 'rgba(220, 53, 69, 0.8)';
      default: return 'rgba(108, 117, 125, 0.8)';
    }
  }};
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  
  &::before {
    content: '';
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
    background-color: ${props => {
      switch(props.status) {
        case MqttConnectionStatus.CONNECTED: return '#28a745';
        case MqttConnectionStatus.CONNECTING: return '#ffc107';
        case MqttConnectionStatus.RECONNECTING: return '#ffc107';
        case MqttConnectionStatus.ERROR: return '#dc3545';
        default: return '#6c757d';
      }
    }};
    box-shadow: 0 0 5px ${props => {
      switch(props.status) {
        case MqttConnectionStatus.CONNECTED: return '#28a745';
        case MqttConnectionStatus.CONNECTING: return '#ffc107';
        case MqttConnectionStatus.RECONNECTING: return '#ffc107';
        case MqttConnectionStatus.ERROR: return '#dc3545';
        default: return '#6c757d';
      }
    }};
  }
`;

// 无人机详情信息悬浮框样式
const DroneInfoPopup = styled.div<{ visible: boolean }>`
  position: absolute;
  right: 23%;
  top: 150px;
  width: 280px;
  background: rgba(0, 21, 41, 0.85);
  color: white;
  border-radius: 4px;
  padding: 10px;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(24, 144, 255, 0.7);
  display: ${props => props.visible ? 'block' : 'none'};
  backdrop-filter: blur(4px);
  
  &::after {
    content: '';
    position: absolute;
    top: -10px;
    right: 20px;
    border-width: 0 10px 10px;
    border-style: solid;
    border-color: transparent transparent rgba(24, 144, 255, 0.7);
  }
`;

const DroneInfoHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(24, 144, 255, 0.3);
  padding-bottom: 5px;
  margin-bottom: 8px;
`;

const DroneTitle = styled.div`
  font-size: 14px;
  font-weight: 500;
  color: #1890ff;
`;

const CloseButton = styled.button`
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 16px;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  
  &:hover {
    color: white;
  }
`;

const InfoRow = styled.div`
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
`;

const InfoLabel = styled.span`
  color: #a0cfff;
`;

const InfoValue = styled.span`
  color: white;
  font-weight: 500;
`;

// 图标样式 - 用于无人机类型判断
const DroneTypeIcon = {
  default: '/images/dashboard/icons/drone-icon.svg',
  // 可以根据无人机类型增加不同图标
  DJI: '/images/dashboard/icons/dji-icon.svg',
};

// 组件Props接口
interface RealtimeDroneLayerProps {
  viewer?: Cesium.Viewer | null;
}

// 定义无人机实体状态映射
interface DroneEntityState {
  [droneId: string]: {
    entity: Cesium.Entity;
    lastPosition: Cesium.Cartesian3;
    lastUpdate: number;
  };
}

// 无人机数据显示组件
export default function RealtimeDroneLayer({ viewer }: RealtimeDroneLayerProps) {
  // MQTT连接状态
  const [connectionStatus, setConnectionStatus] = useState<MqttConnectionStatus>(MqttConnectionStatus.DISCONNECTED);
  
  // 无人机数据状态
  const [droneData, setDroneData] = useState<Record<string, DroneLocationData>>({});
  
  // 无人机实体引用 - 用于平滑动画
  const droneEntitiesRef = useRef<DroneEntityState>({});
  
  // 保存动画帧请求ID，用于清理
  const animationFrameRef = useRef<number | null>(null);
  
  // 单个无人机详情显示状态
  const [selectedDroneId, setSelectedDroneId] = useState<string | null>(null);
  
  // 平滑动画插值持续时间(毫秒)
  const ANIMATION_DURATION = 1000;
  
  // 初始化MQTT连接和事件监听
  useEffect(() => {
    // 状态变化回调函数
    const handleStatusChange = (status: MqttConnectionStatus) => {
      console.log(`MQTT连接状态: ${status}`);
      setConnectionStatus(status);
    };
    
    // 数据变化回调函数
    const handleDroneDataChange = (data: Record<string, DroneLocationData>) => {
      console.log('收到无人机实时位置数据:', data);
      setDroneData(data);
    };
    
    // 初始化无人机位置服务（如果已连接则不会重新连接）
    droneLocationService.initialize();
    
    // 监听连接状态变化
    droneLocationService.onConnectionStatusChange(handleStatusChange);
    
    // 监听无人机数据变化
    droneLocationService.onDroneDataChange(handleDroneDataChange);
    
    // 组件卸载时清理
    return () => {
      // 取消状态监听
      droneLocationService.offConnectionStatusChange(handleStatusChange);
      droneLocationService.offDroneDataChange(handleDroneDataChange);
      
      // 注意：我们不再在这里断开MQTT连接，因为其他组件可能仍需要用到
      // 仅清理本组件相关的资源
      
      // 清理动画循环
      if (animationFrameRef.current !== null) {
        cancelAnimationFrame(animationFrameRef.current);
      }
      
      // 清理无人机实体
      Object.keys(droneEntitiesRef.current).forEach(droneId => {
        if (viewer) {
          viewer.entities.remove(droneEntitiesRef.current[droneId].entity);
        }
      });
    };
  }, [viewer]);
  
  // 处理无人机点击事件
  const handleDroneClick = (droneId: string) => {
    setSelectedDroneId(prevId => prevId === droneId ? null : droneId);
  };
  
  // 关闭无人机信息面板
  const handleCloseInfo = () => {
    setSelectedDroneId(null);
  };
  
  // 飞向选中的无人机
  const flyToDrone = (droneId: string) => {
    if (!viewer || !droneData[droneId]) return;
    
    const drone = droneData[droneId];
    const position = Cesium.Cartesian3.fromDegrees(
      drone.drone_gps_lng,
      drone.drone_gps_lat,
      drone.drone_height + 100 // 高出无人机100米
    );
    
    viewer.camera.flyTo({
      destination: position,
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-45),
        roll: 0
      },
      duration: 2
    });
  };
  
  // 管理无人机实体 - 添加、更新或移除
  useEffect(() => {
    if (!viewer) return;
    
    // 当前时间戳
    const now = Date.now();
    
    // 处理每个无人机数据
    Object.entries(droneData).forEach(([droneId, drone]) => {
      // 计算无人机位置
      const position = Cesium.Cartesian3.fromDegrees(
        drone.drone_gps_lng,
        drone.drone_gps_lat,
        drone.drone_height
      );
      
      // 如果实体已存在，更新数据
      if (droneEntitiesRef.current[droneId]) {
        const droneState = droneEntitiesRef.current[droneId];
        
        // 更新上一个位置和时间戳
        droneState.lastPosition = droneState.entity.position?.getValue(Cesium.JulianDate.now()) as Cesium.Cartesian3;
        droneState.lastUpdate = now;
        
        // 更新实体位置 (动画是在单独的效果中处理的)
        droneState.entity.position = new Cesium.ConstantPositionProperty(position);
        
        // 更新标签
        if (droneState.entity.label) {
          droneState.entity.label.text = new Cesium.ConstantProperty(`${drone.model}\n高度: ${drone.drone_height.toFixed(1)}m`);
        }
      } 
      // 否则创建新实体
      else {
        // 创建无人机图标实体
        const entity = viewer.entities.add({
          id: `drone-${droneId}`,
          position: new Cesium.ConstantPositionProperty(position),
          billboard: {
            image: DroneTypeIcon.default, // 默认图标
            width: 32,
            height: 32,
            scaleByDistance: new Cesium.NearFarScalar(1000, 1, 10000, 0.5),
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          },
          label: {
            text: `${drone.model}\n${drone.gui_id}\n高度: ${drone.drone_height.toFixed(1)}m`,
            font: '12px sans-serif',
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.TOP,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            pixelOffset: new Cesium.Cartesian2(0, -60),
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            translucencyByDistance: new Cesium.NearFarScalar(1500, 1, 5000, 0)
          },
          // 添加轨迹线
          path: {
            show: true,
            material: new Cesium.PolylineGlowMaterialProperty({
              glowPower: 0.2,
              color: Cesium.Color.CYAN
            }),
            width: 3,
            leadTime: 0,
            trailTime: 60, // 显示60秒的历史轨迹
          }
        });
        
        // 添加点击事件
        viewer.screenSpaceEventHandler.setInputAction((movement: Cesium.ScreenSpaceEventHandler.PositionedEvent) => {
          const pickedObject = viewer.scene.pick(movement.position);
          if (Cesium.defined(pickedObject) && pickedObject.id === entity) {
            handleDroneClick(droneId);
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        
        // 保存实体引用
        droneEntitiesRef.current[droneId] = {
          entity,
          lastPosition: position,
          lastUpdate: now,
        };
      }
    });
    
    // 检查并移除不再存在的无人机
    Object.keys(droneEntitiesRef.current).forEach(droneId => {
      if (!droneData[droneId]) {
        // 从地图移除
        viewer.entities.remove(droneEntitiesRef.current[droneId].entity);
        // 从引用中移除
        delete droneEntitiesRef.current[droneId];
      }
    });
    
    // 启动平滑动画
    if (animationFrameRef.current === null) {
      const animate = () => {
        const currentTime = Date.now();
        
        // 对每个无人机进行位置插值
        Object.entries(droneEntitiesRef.current).forEach(([droneId, droneState]) => {
          if (!droneData[droneId]) return;
          
          const timeSinceUpdate = currentTime - droneState.lastUpdate;
          if (timeSinceUpdate >= ANIMATION_DURATION) return;
          
          // 计算插值因子 (0-1)
          const t = Math.min(1, timeSinceUpdate / ANIMATION_DURATION);
          
          // 当前位置
          const targetPosition = Cesium.Cartesian3.fromDegrees(
            droneData[droneId].drone_gps_lng,
            droneData[droneId].drone_gps_lat,
            droneData[droneId].drone_height
          );
          
          // 插值计算
          const interpolatedPosition = new Cesium.Cartesian3();
          Cesium.Cartesian3.lerp(
            droneState.lastPosition,
            targetPosition,
            t,
            interpolatedPosition
          );
          
          // 更新实体位置
          droneState.entity.position = new Cesium.ConstantPositionProperty(interpolatedPosition);
        });
        
        // 继续动画循环
        animationFrameRef.current = requestAnimationFrame(animate);
      };
      
      // 开始动画循环
      animationFrameRef.current = requestAnimationFrame(animate);
    }
    
    // 清理动画循环
    return () => {
      if (animationFrameRef.current !== null) {
        cancelAnimationFrame(animationFrameRef.current);
        animationFrameRef.current = null;
      }
    };
  }, [droneData, viewer]);
  
  // 渲染选中无人机的详情信息
  const selectedDrone = selectedDroneId ? droneData[selectedDroneId] : null;
  
  return (
    <>
      {/* MQTT连接状态指示器 */}
      <ConnectionStatus status={connectionStatus}>
        {connectionStatus === MqttConnectionStatus.CONNECTED && '无人机数据已连接'}
        {connectionStatus === MqttConnectionStatus.CONNECTING && '正在连接数据...'}
        {connectionStatus === MqttConnectionStatus.RECONNECTING && '重新连接中...'}
        {connectionStatus === MqttConnectionStatus.ERROR && '连接错误'}
        {connectionStatus === MqttConnectionStatus.DISCONNECTED && '未连接'}
      </ConnectionStatus>
      
      {/* 无人机信息弹窗 */}
      <DroneInfoPopup visible={Boolean(selectedDrone)}>
        {selectedDrone && (
          <>
            <DroneInfoHeader>
              <DroneTitle>{selectedDrone.model}</DroneTitle>
              <CloseButton onClick={handleCloseInfo}>×</CloseButton>
            </DroneInfoHeader>
            
            <InfoRow>
              <InfoLabel>SN码:</InfoLabel>
              <InfoValue>{selectedDrone.gui_id}</InfoValue>
            </InfoRow>
            
            <InfoRow>
              <InfoLabel>侦测雷达ID:</InfoLabel>
              <InfoValue>{selectedDrone.sensor_id}</InfoValue>
            </InfoRow>
            
            <InfoRow>
              <InfoLabel>高度:</InfoLabel>
              <InfoValue>{selectedDrone.drone_height.toFixed(1)} 米</InfoValue>
            </InfoRow>
            
            {/*<InfoRow>*/}
            {/*  <InfoLabel>方位角:</InfoLabel>*/}
            {/*  <InfoValue>{selectedDrone.drone_azimuth.toFixed(1)}°</InfoValue>*/}
            {/*</InfoRow>*/}
            
            {/*<InfoRow>*/}
            {/*  <InfoLabel>距离:</InfoLabel>*/}
            {/*  <InfoValue>{selectedDrone.drone_distance.toFixed(1)} 米</InfoValue>*/}
            {/*</InfoRow>*/}
            
            <InfoRow>
              <InfoLabel>坐标:</InfoLabel>
              <InfoValue>
                {selectedDrone.drone_gps_lat.toFixed(6)}, {selectedDrone.drone_gps_lng.toFixed(6)}
              </InfoValue>
            </InfoRow>
            
            <InfoRow>
              <InfoLabel>时间:</InfoLabel>
              <InfoValue>{selectedDrone.created_at}</InfoValue>
            </InfoRow>
            
            <InfoRow style={{ justifyContent: 'center', marginTop: '10px' }}>
              <button 
                onClick={() => selectedDroneId && flyToDrone(selectedDroneId)}
                style={{
                  backgroundColor: 'rgba(24, 144, 255, 0.3)',
                  border: '1px solid rgba(24, 144, 255, 0.7)',
                  borderRadius: '4px',
                  padding: '4px 8px',
                  color: 'white',
                  cursor: 'pointer',
                  fontSize: '12px'
                }}
              >
                飞向此无人机
              </button>
            </InfoRow>
          </>
        )}
      </DroneInfoPopup>
    </>
  );
} 